import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shop/shop/life/AddDizhi.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shop/shop/life/LjgmOrder.dart';

import 'EditAddress.dart';
import 'Login.dart';

class DizhiGuanli extends StatefulWidget {
  int type; //下订单页面跳转1：立即购买页面  2：购物车结算页面
  String gid; //商品ID
  String names; //规格
  String params; //规格下标
  double money; //选定规格金额
  int num; //数量
  double allMoney; //总金额
  String orRemark; //订单备注
  DizhiGuanli(
      {Key key,
      this.title,
      this.type,
      this.gid,
      this.names,
      this.params,
      this.money,
      this.num,
      this.allMoney,
      this.orRemark})
      : super(key: key);

  final String title;
  bool isDefault = false; // 是否为默认地址
  @override
  _DizhiGuanli createState() =>
      _DizhiGuanli(type, gid, names, params, money, num, allMoney, orRemark);
}

class _DizhiGuanli extends State<DizhiGuanli> {
  List dizhis = [];
  String userId; //用户ID
  int type; //下订单页面跳转1：立即购买页面  2：购物车结算页面
  String gid; //商品ID
  String names; //规格
  String params; //规格下标
  double money; //选定规格金额
  int num; //数量
  double allMoney; //总金额
  String orRemark; //订单备注
  // 构造函数
  _DizhiGuanli(type, gid, names, params, money, num, allMoney, orRemark) {
    this.type = type;
    this.gid = gid;
    this.names = names;
    this.params = params;
    this.money = money;
    this.num = num;
    this.allMoney = allMoney;
    this.orRemark = orRemark;
    isLogin();
  }

  // 判断是否登录
  Future<void> isLogin() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if (prefs.getBool("isLogin") == false) {
      Fluttertoast.showToast(
          msg: "请先登录",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.black45,
          textColor: Colors.white,
          fontSize: 16.0);
      MyRoute.replace(Login());
    } else {
      _onLoading();
    }
  }


  final SlidableController slidableController = SlidableController(); // 滑动控制器

  // 加载数据的函数
  void _onLoading() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    userId = prefs.getString("userId");
    // 发起请求
    var x =
        await HttpUtil().get("/app/address/searchUserAddress?userId=${userId}");
    if (x['code'] == 200) {
      dizhis.addAll(x['data']);
    }

    // if failed,use loadFailed(),if no data return,use LoadNodata()
    if (mounted) {
      setState(() {});
    }
  }

  // 动态显示收货地址
  Widget _showDizhi(item, index) {
    return GestureDetector(
      onTap: () async {
        String id = item['id']; //收货地址ID
        //设置默认收货地址
        if (type == 1) {
          MyRoute.push(LjgmOrder(
            adId: id,
            gid: gid,
            num: num,
            names: names,
            params: params,
            money: money,
            allMoney: allMoney,
            orRemark: orRemark,
          )); //跳立即购买页面
          return;
        } else if (type == 2) {
          Map map = new Map();
          map['adName'] = item['adName'];
          map['adPhone'] = item['adPhone'];
          map['addressDetail'] = item['addressDetail'];
          map['id'] = item['id'];
          MyRoute.pop(map); //跳购物车结算页面
          return;
        }
        // await HttpUtil().get("/app/address/updateAddressStatus?id="+id+"&userId="+userId+"&adStatus=1");
        if (item['adStatus'] == 1) {
          Fluttertoast.showToast(
              msg: "已是默认收货地址",
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.BOTTOM,
              timeInSecForIosWeb: 1,
              backgroundColor: Colors.black45,
              textColor: Colors.white,
              fontSize: 16.0);
          return;
        }
        showDialog<Null>(
          context: context,
          barrierDismissible: false,
          builder: (BuildContext context) {
            return new AlertDialog(
              title: new Text('修改默认收货地址'),
              content: Text('确定修改?'),
              actions: <Widget>[
                new FlatButton(
                  child: new Text('取消'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
                new FlatButton(
                  child: new Text('确定'),
                  onPressed: () async {
                    Navigator.of(context).pop();
                    String id = dizhis[index]['id'];
                    var x = await HttpUtil().get(
                        "/app/address/updateAddressStatus?id=" +
                            id +
                            "&userId=" +
                            userId +
                            "&adStatus=1");
                    if (x['code'] == 200) {
                      setState(() {
                        // dizhis.removeRange(0,dizhis.length);
                        // _onLoading();//可以
                        for (int i = 0; i < dizhis.length; i++) {
                          dizhis[i]['adStatus'] = 0;
                        }
                        dizhis[index]['adStatus'] = 1; //可以
                      });
                    } else {
                      Fluttertoast.showToast(
                          msg: x['msg'],
                          toastLength: Toast.LENGTH_SHORT,
                          gravity: ToastGravity.BOTTOM,
                          timeInSecForIosWeb: 1,
                          backgroundColor: Colors.black45,
                          textColor: Colors.white,
                          fontSize: 16.0);
                    }
                    setState(() {});
                  },
                ),
              ],
            );
          },
        ).then((val) {
          print(val);
        });
      },
      child: Container(
          child: Slidable(
              controller: slidableController,
              actionPane: SlidableDrawerActionPane(),
              actionExtentRatio: 0.25,
              child: Column(
                  children: [
                Container(
                    padding: EdgeInsets.only(top: 10,left: 10,right: 10),
                    child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        item['adName'],
                        style: TextStyle(color: Colors.blue, fontSize: 22),
                      ),
                      Text(item['adPhone'], style: TextStyle(height: 1.1)),
                    ])),
                SizedBox(height: 10,),
                Container(
                  padding: EdgeInsets.only(bottom: 10,left: 10,right: 10),
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Container(
                          margin: EdgeInsets.only(top: 10),
                          padding: item['adStatus'] == 1
                              ? EdgeInsets.fromLTRB(8, 3, 8, 3)
                              : null,
                          decoration: BoxDecoration(
                              color: Colors.blue,
                              borderRadius: BorderRadius.circular(5)),
                          child: Text(item['adStatus'] == 1 ? "默认" : '',
                              style: TextStyle(color: Colors.white,fontSize: 14)),
                        ),
                        Expanded(
                          child: Container(
                            // margin: EdgeInsets.only(top:20),
                            padding: EdgeInsets.fromLTRB(10, 5, 10, 5),
                            child: Text(item['addressDetail'],
                                style: TextStyle(height: 1.1)),
                          ),
                        )
                      ]
                  ),
                )
              ]),
              secondaryActions: [
            IconSlideAction(
                caption: '编辑',
                color: Colors.black38,
                icon: Icons.edit_location_outlined,
                onTap: () async {
                  SharedPreferences prefs = await SharedPreferences.getInstance();
                    prefs.setString("dizhiId", item['id']);
                    List value = await MyRoute.push(EditAddress());
                    setState(() {
                      if(value!=null)
                      {  if(value[3]==1){
                          for(var i=0; i<dizhis.length;i++){
                            dizhis[i]['adStatus']=0;
                          }
                        }
                        item['adPhone']=value[2];
                        item['adName']=value[1];
                        item['addressDetail']=value[0];
                        item['adStatus']=value[3];
                      }
                    });
                }),
            IconSlideAction(
                caption: '删除',
                color: Colors.redAccent,
                icon: Icons.remove_circle_outline,
                onTap: () {
                  showDialog<Null>(
                                    context: context,
                                    barrierDismissible: false,
                                    builder: (BuildContext context) {
                                      return new AlertDialog(
                                        title: new Text('删除该收货地址'),
                                        content: Text('确定删除?'),
                                        actions: <Widget>[
                                          new FlatButton(
                                            child: new Text('取消'),
                                            onPressed: (){
                                              Navigator.of(context).pop();
                                            },
                                          ),
                                          new FlatButton(
                                            child: new Text('确定'),
                                            onPressed: () async{
                                              Navigator.of(context).pop();
                                              String addressid = dizhis[index]['id'];
                                              // SharedPreferences prefs = await SharedPreferences.getInstance();
                                              // String userId = prefs.getString("userId");
                                              var x = await HttpUtil().get("/app/address/deleteAddress?userId=${userId}&id=${addressid}");
                                              if(x['code']==200){
                                                Fluttertoast.showToast(
                                                    msg: x['msg'],
                                                    toastLength: Toast.LENGTH_SHORT,
                                                    gravity: ToastGravity.BOTTOM,
                                                    timeInSecForIosWeb: 1,
                                                    backgroundColor: Colors.black45,
                                                    textColor: Colors.white,
                                                    fontSize: 16.0
                                                );
                                                setState(() {
                                                  for(int i=0;i<dizhis.length;i++){
                                                    print("dizhis[i][id]="+dizhis[i]['id']);
                                                    if(dizhis[i]['id']==addressid){
                                                      dizhis.remove(dizhis[i]);
                                                    }
                                                  }
                                                });
                                              }else{
                                                Fluttertoast.showToast(
                                                    msg: x['msg'],
                                                    toastLength: Toast.LENGTH_SHORT,
                                                    gravity: ToastGravity.BOTTOM,
                                                    timeInSecForIosWeb: 1,
                                                    backgroundColor: Colors.black45,
                                                    textColor: Colors.white,
                                                    fontSize: 16.0
                                                );
                                              }
                                              setState(() {

                                              });
                                            },
                                          ),
                                        ],
                                      );
                                    },
                                  ).then((val) {
                                    print(val);
                                  });
                })
          ])),
    );
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 464, height: 820);
    return Scaffold(
      appBar: AppBar(
        title: Text("我的地址"),
      ),
      body: Container(
        child: Column(
          children: [
            GestureDetector(
              child: Container(
                height: 50,
                width: 480,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      child: Row(
                        children: [
                          Container(
                            child: Icon(Icons.location_history),
                          ),
                          Container(
                            child: Text("新增地址"),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      child: Icon(Icons.arrow_forward_ios_outlined),
                    )
                  ],
                ),
              ),
              behavior: HitTestBehavior.opaque,
              onTap: () async {
                Map value = await MyRoute.push(AddDizhi());
                if(value!=null){
                  setState(() {
                    if (value['adStatus'] == 1) {
                      for (var i = 0; i < dizhis.length; i++) {
                        dizhis[i]['adStatus'] = 0;
                      }
                    }
                    dizhis.add(value);
                  });
                }
              },
            ),
            Expanded(
                child: Container(
              child: ListView.builder(
                itemBuilder: (c, i) => Card(child: _showDizhi(dizhis[i], i)),
                itemCount: dizhis.length,
              ),
            ))
          ],
        ),
      ),
    );
  }
}
